<?php
class MY_Model extends CI_Model {
	
		var $TABLE = "";
		
		function __construct(){
			parent::__construct();
			$this->TABLE = get_called_class();
		}
	
		function table(){
			if(preg_match('/_model$/', $this->TABLE)==1) {
				$tablename = str_replace("_model", "", $this->TABLE);
			} else {
				show_error("Naming convention model class must be 'tablename_model'",500,"Error Model Name");
			}
			return strtolower($tablename);
			
		}
	
		function lastInsertedId(){
			return $this->db->insert_id();
		}
	
		function insert($record = array()){
			if(count($record) > 0){
				$record['is_valid'] = VALID;
				$record['create_date'] = date("d/m/y : H:i:s", time());
				$record['update_date'] = date("d/m/y : H:i:s", time());
				$record['created_by'] = '';//current user
				$record['updated_by'] = '';//current user
				$this->db->insert($this->table() , $record);
			}
		}
	
		function update($record = array()){
			if(count($record) > 0 && isset($record['id'])){
				$record['update_date'] = date("d/m/y : H:i:s", time());
				$record['updated_by'] = '';//current user
				$this->db->where("id" , $record['id']);
				$this->db->where("is_valid", VALID);
				$this->db->update($this->table() , $record);
			}
		}
	
		function delete($id){
			if( $id != null && $id != ""){
				$this->db->set("is_valid" , DELETED);
				$this->db->where("id" , $id);
				$this->db->where("is_valid", VALID);
				$this->db->update($this->table());
			}
		}
	
	
		function findById( $id){
			$this->db->select("*");
			$this->db->where("id", $id);
			$result = $this->db->get($this->table());
			return $result->row_array();
		}
	
	
		function search($data = array(), $matchAll = FALSE){
			if($matchAll)
				$this->db->like($data);//all conditions must be satisfied
			else
				$this->db->or_like($data);//not all conditions must be satisfied
			$this->db->where("is_valid", VALID);
			$result = $this->db->get($this->table());
			return $result->result_array();
		}
	
	}